package com.su.song.dataapplication.databass;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.su.song.dataapplication.enity.User;

public class UserDBHeaper extends SQLiteOpenHelper {

    private static final String DB_NAME = "uer.db";//数据库名称
    private static final int DB_VERSION = 1;//数据库版本
    private static final String TABLE_NAME = "user_info";//用户表的名称
    private static UserDBHeaper mHelper = null;
    private SQLiteDatabase mRDB = null;
    private SQLiteDatabase mWDB = null;

    //调用父类的构造方法
    private UserDBHeaper(Context context){
        super(context,DB_NAME,null,DB_VERSION);
    }

    //单例模式构造方法
    public static UserDBHeaper getInstance(Context context){
        if(mHelper == null){
            mHelper = new UserDBHeaper(context);
        }
        return mHelper;
    }

    //打开数据库读连接
    public SQLiteDatabase opeaReadLink(){
        if(mRDB == null || !mRDB.isOpen()){
            mRDB = mHelper.getReadableDatabase();
        }
        return mRDB;
    }
    //打开数据库写连接
    public SQLiteDatabase opeaWriteLink(){
        if(mWDB == null || !mWDB.isOpen()){
            mWDB = mHelper.getWritableDatabase();
        }
        return mWDB;
    }
    //关闭数据库连接
    public void closeLink(){
        if(mRDB != null && mRDB.isOpen()){
            mRDB.close();
            mRDB = null;
        }
        if(mWDB != null && mWDB.isOpen()){
            mWDB.close();
            mWDB = null;
        }
    }



//创建数据库，执行建表语句
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(" +
                "  id INT  PRIMARY KEY  AUTOINCREMENT  NOT NULL ," +
                "  name CHAR NOT NULL," +
                "  age INT NOT NULL," +
                "  height LONG NOT NULL," +
                "  weight FLOAT NOT NULL," +
                "  married INT NOT NULL);";


//        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
//                "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
//                " name VARCHAR NOT NULL," +
//                " age INTEGER NOT NULL," +
//                " height LONG NOT NULL," +
//                " weight FLOAT NOT NULL," +
//                " married INTEGER NOT NULL);";
          db.execSQL(sql);
    }
//操作数据库
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insert(User user){
        ContentValues values = new ContentValues();
        values.put("name",user.name);
        values.put("age",user.age);
        values.put("height",user.height);
        values.put("weight",user.weight);
        values.put("married",user.married);
        return mWDB.insert(TABLE_NAME,null,values);
    }
}
